package com.java.main.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.java.main.domain.token.TokenDO;
import com.java.main.service.token.TokenService;
import com.java.main.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.java.main.constant.Errors;
import com.java.main.controller.BaseController;
import com.java.main.controller.input.DataInput;
import com.java.main.controller.output.BaseOutput;
import com.java.main.controller.output.ResultResponseBeanUtil;
import com.java.main.domain.KbmContent;

import com.java.main.domain.user.UserDO;
import com.java.main.domain.user.UserEntryDO;
import com.java.main.domain.user.UserEntryRepository;
import com.java.main.domain.user.UserRepository;
import com.java.main.exception.HiBabyGlobalException;
//import com.hibaby.crm.util.JedisUtil;
import com.java.main.util.OSSUploadUtil;
import com.java.main.util.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "用户接口", description = "用户接口-王月强", produces = "application/json")
@Controller
public class UserController extends BaseController {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Value("${encrypt_algorithm}")
	private String encryptAlgorithm;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserService userService;
	@Autowired
	private UserEntryRepository userEntryRepository;
	@Autowired
	private TokenService tokenService;

	@ApiOperation(value = "用户登录", notes = "用户登录")
	@ResponseBody
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public BaseOutput<LoginOutput> login(@Valid @RequestBody LoginInput input) {
		LoginOutput output = null;
//		UserDO entity = userRepository.findByMobile(input.getMobile());
		UserDO entity = userService.findByUserAccount(input.getUserAccount());
		if (entity == null) {
			throw new HiBabyGlobalException(Errors.USER_NOT_EXIST);
		}
		// if (entity.getStatus() == 1) {
		// throw new HiBabyGlobalException(Errors.NOT_PERMISSION, "禁止登录");
		// }
		String password = StringUtils.encrypt(input.getPassword(), encryptAlgorithm);
		if (!password.equals(entity.getPassword())) {
			throw new HiBabyGlobalException(Errors.PASSWORD_ERROR);
		} else {
			// 生成token并绑定用户id存在token表中
			String token = tokenService.getTokenByUser(entity);
//			// output = (LoginOutput)
//			// JedisUtil.getObj(Constants.CURRENT_SYS_USER_TOKEN + token);
			if (token != null) {
				output = new LoginOutput();
				output.setUserAccount(entity.getUserAccount());
				output.setMobile(entity.getMobile());
				output.setToken(token);
				// 保存token
//				JedisUtil.setObj(Constants.CURRENT_SYS_USER_TOKEN + token, content);
			}
		}
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "用户注册", notes = "用户注册")
	@ResponseBody
	@RequestMapping(value = "/user/signup", method = RequestMethod.POST)
	public BaseOutput<LoginOutput> signup(@Valid @RequestBody LoginInput input) {

		UserDO userDO = userService.findByUserAccount(input.getUserAccount());
		// 用户已存在
		if (userDO != null) {
			throw new HiBabyGlobalException(Errors.USER_EXISTED);
		}
		UserDO entity = userService.createUser(input.getMobile(),input.getUserAccount(),input.getPassword());
		//	用户创建失败
		if (entity == null) {
			throw new HiBabyGlobalException(Errors.SIGN_UP_ERROR);
		}
		// if (entity.getStatus() == 1) {
		// throw new HiBabyGlobalException(Errors.NOT_PERMISSION, "禁止登录");
		// }

		LoginOutput output = new LoginOutput();
		output.setUserAccount(entity.getUserAccount());
		output.setMobile(entity.getMobile());

		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "验证用户登录状态", notes = "验证用户登录状态")
	@ResponseBody
	@RequestMapping(value = "/user/isLogin", method = RequestMethod.POST)
	public BaseOutput<LoginOutput> isLogin(HttpServletRequest request) {
		// 能进来验证就证明token有效,
		String userToken = request.getHeader("USER-TOKEN");
		TokenDO tokenDO = tokenService.findByToken(userToken);

		UserDO userDO = userService.findById(tokenDO.getUserId());
		// 用户不存在
		if (userDO == null) {
			tokenService.deleteTokenDObyToken(userToken);
			throw new HiBabyGlobalException(Errors.NOT_LOGIN);
		}

		LoginOutput output = new LoginOutput();
		output.setUserAccount(userDO.getUserAccount());
		output.setMobile(userDO.getMobile());
		return ResultResponseBeanUtil.success(output);
	}

	@ResponseBody
	@RequestMapping(value = "/user/list", method = RequestMethod.POST)
	public BaseOutput<List<UserDO>> list(HttpServletRequest request) {
		KbmContent content = getCurrentInfo(request);
		log.info("当前用户ID" + content.getCurrentUserId());
		List<UserDO> list = userRepository.findAll();
		return ResultResponseBeanUtil.success(list);
	}

	@ApiOperation(value = "获取手机验证码", notes = "获取手机验证码")
	@ResponseBody
	@RequestMapping(value = "/user/getVerCode", method = RequestMethod.POST)
	public BaseOutput<Void> getVerCode(@Valid @RequestBody GetVerCodeInput input) {
		UserDO entity = userService.findByMobile(input.getMobile());
		if (entity == null) {
			throw new HiBabyGlobalException(Errors.USER_NOT_EXIST);
		}
		// if (entity.getStatus() == 1) {
		// throw new HiBabyGlobalException(Errors.SYSTEM_ERROR, "该用户已禁用");
		// }
//		smsRecordService.sendVerCode(input.getMobile());
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "重置验证码", notes = "重置验证码")
	@ResponseBody
	@RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
	public BaseOutput<Void> resetPassword(@Valid @RequestBody ResetPasswordInput input) {
		if (input.getVerCode() == null) {
			throw new HiBabyGlobalException(Errors.VERCODE_EMPTY);
		}
//		if (!smsRecordService.checkVerCode(input.getMobile(), input.getVerCode())) {
//			throw new HiBabyGlobalException(Errors.VER_CODE_FAIL);
//		}

		UserDO entity = userRepository.findByMobile(input.getMobile());
		if (entity == null) {
			throw new HiBabyGlobalException(Errors.USER_NOT_EXIST);
		}
		KbmContent kbmContent = new KbmContent();
		kbmContent.setCurrentUserId(entity.getId());
		entity.setKbmContent(kbmContent);
		String password = input.getPassword();
		password = StringUtils.encrypt(password, encryptAlgorithm);
		entity.setPassword(password);
		userService.update(entity);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "根据id查询用户信息", notes = "根据id查询用户信息")
	@ResponseBody
	@RequestMapping(value = "/user/getUserListById", method = RequestMethod.POST)
	public BaseOutput<UserDO> getUserListById(HttpServletRequest request, @Valid @RequestBody UserInfoInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		UserDO userDO = userService.findUserListById(input, kbmContent);
		userDO.setPassword("*****");
		if (userDO != null && !StringUtils.isBlank(userDO.getImg())) {
			String url = OSSUploadUtil.getUrl(userDO.getImg());
			userDO.setImgURL(url);
		}
		return ResultResponseBeanUtil.success(userDO);
	}

	@ApiOperation(value = "根据id查询个人档案信息", notes = "根据id查询个人档案信息")
	@ResponseBody
	@RequestMapping(value = "/user/getUserInfoById", method = RequestMethod.POST)
	public BaseOutput<UserDO> getUserInfoById(HttpServletRequest request, @Valid @RequestBody DataInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		UserDO userDO = userService.findUserInfoById(input.getDataId(), kbmContent);
		userDO.setPassword("*****");
		if (userDO != null && !StringUtils.isBlank(userDO.getImg())) {
			String url = OSSUploadUtil.getUrl(userDO.getImg());
			userDO.setImgURL(url);
		}
		return ResultResponseBeanUtil.success(userDO);
	}

	@ApiOperation(value = "加载登录用户信息", notes = "加载登录用户信息")
	@ResponseBody
	@RequestMapping(value = "/user/getCurrentUserInfo", method = RequestMethod.POST)
	public BaseOutput<UserDO> getCurrentUserInfo(HttpServletRequest request) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		UserDO userDO = userService.findLoginUserListById(kbmContent.getCurrentUserId(), kbmContent);
		userDO.setPassword("*****");
		if (userDO != null && !StringUtils.isBlank(userDO.getImg())) {
			String url = OSSUploadUtil.getUrl(userDO.getImg());
			userDO.setImgURL(url);
		}
		UserEntryDO entry = userEntryRepository.findByUserIdAndEndemicIdAndTypeAndSoftDelete(userDO.getId(),
				kbmContent.getEndemicId(), 0, 0);
		List<UserEntryDO> entryList = new ArrayList<UserEntryDO>();
		entryList.add(entry);
		userDO.setEntrys(entryList);
		return ResultResponseBeanUtil.success(userDO);
	}

	@ApiOperation(value = "新增用户信息", notes = "新增用户信息")
	@ResponseBody
	@RequestMapping(value = "/user/addUser", method = RequestMethod.POST)
	public BaseOutput<UserPointOutput> addUser(HttpServletRequest request, @Valid @RequestBody UserDO userDO) {
		UserPointOutput output = new UserPointOutput();
		String str = "";
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userDO.setKbmContent(kbmContent);
		UserDO userDO2 = userRepository.findByMobile(userDO.getMobile());
		if (userDO2 == null) {
			userService.saveUser(userDO);
			output.setType(1);
		} else {
			UserEntryDO userEntry = userEntryRepository.findByUserIdAndEndemicIdAndTypeAndSoftDelete(userDO2.getId(),
					kbmContent.getEndemicId(), 0, 0);
			if (userEntry != null) {
				output.setType(2);
			} else {
				List<UserEntryDO> list = userEntryRepository.findByUserIdAndType(userDO2.getId(), 0);
				str = str.substring(1, str.length());
				output.setName(userDO2.getName());
				output.setEndemicName(str);
				output.setType(3);
			}
		}

		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "添加用户入职信息", notes = "添加用户入职信息")
	@ResponseBody
	@RequestMapping(value = "/user/addUserEntry", method = RequestMethod.POST)
	public BaseOutput<Void> addUserEntry(HttpServletRequest request, @Valid @RequestBody UserEntryDO userEntryDO) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userEntryDO.setKbmContent(kbmContent);
		userEntryDO.setEndemicId(kbmContent.getEndemicId());
		userService.saveUserEntry(userEntryDO);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "修改个人档案入职信息联系方式", notes = "修改个人档案入职信息联系方式")
	@ResponseBody
	@RequestMapping(value = "/user/updateUserEntry", method = RequestMethod.POST)
	public BaseOutput<Void> updateUserEntry(HttpServletRequest request, @Valid @RequestBody UserEntryInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userService.updateUserEntry(input, kbmContent);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "修改用户信息", notes = "修改用户信息")
	@ResponseBody
	@RequestMapping(value = "/user/modifyUser", method = RequestMethod.POST)
	public BaseOutput<Void> modifyUser(HttpServletRequest request, @Valid @RequestBody UserDO userDO) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userDO.setKbmContent(kbmContent);
		userService.modifyUser(userDO);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "根据用户id禁用用户", notes = "根据用户id禁用用户")
	@ResponseBody
	@RequestMapping(value = "/user/forbiddenUser", method = RequestMethod.POST)
	public BaseOutput<Void> forbiddenUser(HttpServletRequest request, @Valid @RequestBody DataInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userService.forbiddenUser(input.getDataId(), kbmContent);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "根据入职信息id删除入职信息", notes = "根据入职信息id删除入职信息")
	@ResponseBody
	@RequestMapping(value = "/user/deleteUserEntry", method = RequestMethod.POST)
	public BaseOutput<Void> deleteUserEntry(HttpServletRequest request, @Valid @RequestBody DataInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		userService.deleteUserEntry(input.getDataId(), kbmContent);
		return ResultResponseBeanUtil.success();
	}


//	@ApiOperation(value = "根据条件查询所有用户分页信息", notes = "根据条件查询所有用户分页信息")
//	@ResponseBody
//	@RequestMapping(value = "/user/getUserPageListByDeptId", method = RequestMethod.POST)
//	public PageOutput<UserOutput> getUserPageListByDeptId(HttpServletRequest request,
//			@Valid @RequestBody UserInput input) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		if (input.getNodeid() == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		input.setKbmContent(kbmContent);
//		PageOutput<UserOutput> output = userService.findUserListByUserInput(input);
//		return ResultResponseBeanUtil.pageSuccess(output.getData(), output.getSize(), output.getPage(),
//				output.getTotal());
//	}

//	@ApiOperation(value = "根据条件查询所有角色授权用户分页信息", notes = "根据条件查询所有角色授权用户分页信息")
//	@ResponseBody
//	@RequestMapping(value = "/user/getUserPageListByUserRole", method = RequestMethod.POST)
//	public PageOutput<UserRoleOutput> getUserPageListByUserRole(HttpServletRequest request,
//			@Valid @RequestBody UserRoleInput input) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		if (input.getNodeid() == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		input.setKbmContent(kbmContent);
//		PageOutput<UserRoleOutput> output = userService.findUserListByUserRoleInput(input);
//		return ResultResponseBeanUtil.pageSuccess(output.getData(), output.getSize(), output.getPage(),
//				output.getTotal());
//	}

//	@ApiOperation(value = "根据系统角色查询所有用户分页信息", notes = "根据系统角色查询所有用户分页信息")
//	@ResponseBody
//	@RequestMapping(value = "/user/getUserPageListByRoleId", method = RequestMethod.POST)
//	public PageOutput<UserOutput> getUserPageListByRoleId(HttpServletRequest request,
//			@Valid @RequestBody RoleInput input) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		input.setKbmContent(kbmContent);
//		PageOutput<UserOutput> output = userService.findUserListByRoleId(input);
//		return ResultResponseBeanUtil.pageSuccess(output.getData(), output.getSize(), output.getPage(),
//				output.getTotal());
//	}

//	@ApiOperation(value = "绑定用户角色", notes = "绑定用户角色,如果用户id为多个则以逗号拼接")
//	@ResponseBody
//	@RequestMapping(value = "/user/bindUserRole", method = RequestMethod.POST)
//	public BaseOutput<Void> bindUserRole(HttpServletRequest request, @Valid @RequestBody UserRoleBindInput input) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		input.setKbmContent(kbmContent);
//		String[] userIds = input.getUserId().split(",");
//		for (int i = 0; i < userIds.length; i++) {
//			UserEntryDO userEntryDO = userEntryRepository.findByUserIdAndEndemicIdAndTypeAndSoftDelete(
//					Integer.valueOf(userIds[i]), kbmContent.getEndemicId(), 0, 0);
//			userService.bindUserRole(input, userIds[i], userEntryDO.getId());
//		}
//		return ResultResponseBeanUtil.success();
//	}



	@ApiOperation(value = "登出系统", notes = "登出系统")
	@RequestMapping(value = "/user/logout", method = RequestMethod.POST)
	@ResponseBody
	public BaseOutput<Void> Logout(HttpServletRequest request) {
//		try {
//			KbmContent kbmContent = getCurrentInfo(request);
//			if (!"testToken".equals(kbmContent.getToken())) {
////				JedisUtil.del(Constants.CURRENT_SYS_USER_TOKEN + kbmContent.getToken());
//				request.getSession().removeAttribute(Constants.CURRENT_SYS_USER_INFO);
//			}
//		} catch (Exception e) {
//			log.info("登出错误" + e.getMessage());
//		}
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "修改密码", notes = "修改密码")
	@RequestMapping(value = "/user/updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public BaseOutput<Void> updatePassword(HttpServletRequest request, @Valid @RequestBody PassWordInput input) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		UserDO userDO = userRepository.findByMobile(input.getMobile());
		String oldpassword = StringUtils.encrypt(input.getOldPassWord(), encryptAlgorithm);
		if (!oldpassword.equals(userDO.getPassword())) {
			throw new HiBabyGlobalException(Errors.OLDPASSWORD_ERROR);
		}
		String newpassword = StringUtils.encrypt(input.getNewPassWord(), encryptAlgorithm);
		userDO.setPassword(newpassword);
		userDO.setKbmContent(kbmContent);
		userService.updatePassWord(userDO);
		return ResultResponseBeanUtil.success();
	}

	@ApiOperation(value = "加载登录用户未读消息数量", notes = "加载登录用户未读消息数量")
	@ResponseBody
	@RequestMapping(value = "/user/getMessageQuantity", method = RequestMethod.POST)
	public BaseOutput<Integer> getMessageQuantity(HttpServletRequest request) {
		KbmContent kbmContent = getCurrentInfo(request);
		if (kbmContent == null) {
			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
		}
		Integer quantity = userService.getMessageQuantity(kbmContent);

		return ResultResponseBeanUtil.success(quantity);
	}

//	@ApiOperation(value = "加载登录用户消息列表", notes = "加载登录用户消息列表")
//	@ResponseBody
//	@RequestMapping(value = "/user/getMessageList", method = RequestMethod.POST)
//	public BaseOutput<List<NotificationUserDO>> getMessageList(HttpServletRequest request) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		List<NotificationUserDO> list = notificationUserRepository
//				.findByUserIdAndSoftDelete(kbmContent.getCurrentUserId(), 0);
//		return ResultResponseBeanUtil.success(list);
//	}

//	@ApiOperation(value = "切换消息未读已读标识", notes = "切换消息未读已读标识")
//	@ResponseBody
//	@RequestMapping(value = "/user/changeMessageType", method = RequestMethod.POST)
//	public BaseOutput<Void> changeMessageType(HttpServletRequest request, @Valid @RequestBody MessageInput input) {
//		KbmContent kbmContent = getCurrentInfo(request);
//		if (kbmContent == null) {
//			throw new HiBabyGlobalException(Errors.LACK_CONTENT);
//		}
//		NotificationUserDO notificationUserDO = notificationUserRepository
//				.findByUserIdAndNotificationIdAndTypeAndSoftDelete(input.getUserId(), input.getNotificationId(),input.getType(),0);
//		notificationUserDO.setKbmContent(kbmContent);
//		userService.changeMessageType(notificationUserDO);
//		return ResultResponseBeanUtil.success();
//	}
}
